package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import util.RowMapper;
import util.UtilDB;
import entity.User;

public class UserDao {
	private UtilDB<User> db = new UtilDB<User>();

	public boolean add(User user) {
		String sql = "insert into user(username,password) values(?,?)";
		return db.executeSQL(sql, user.getUsername(), user.getPassword());
	}

	public boolean del(User user) {
		String sql = "delete from user where id=?";
		return db.executeSQL(sql, user.getId());
	}

	public boolean update(User user) {
		String sql = "update user set username=?,password=? where id=?";
		return db.executeSQL(sql, user.getUsername(), user.getPassword(), user
				.getId());
	}

	public User findUserById(int id) {
		String sql = "select id,username,password from user where id=?";
		return db.executeQueryForObject(sql, new UserRowMapper(), id);
	}
	
	public List<User> findAll(){
		return null;
	}
	
	public User findUserByName(String name) {
		String sql = "select id,username,password from user where username=?";
		return db.executeQueryForObject(sql, new UserRowMapper(), name);
	}

	public List<User> findAllUser() {
		String sql="select id,username,password from user";
		return db.executeQueryForList(sql, new UserRowMapper());
	}

	private class UserRowMapper implements RowMapper<User> {

		public User rowMapper(ResultSet rs) throws SQLException {
			User user = new User();
			user.setId(rs.getInt("id"));
			user.setUsername(rs.getString("username"));
			user.setPassword(rs.getString("password"));
			return user;
		}

	}

}
